package com.example.sx_06.suxuantv

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.TargetApi
import android.content.Intent
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_login.*
import android.text.Editable
import android.text.TextWatcher
import android.text.InputFilter
import android.support.design.widget.CoordinatorLayout.Behavior.setTag
import android.util.Log
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import okhttp3.*
import java.io.IOException
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.SPUtils
import com.example.sx_06.suxuantv.cookie.CookieUtil
import com.example.sx_06.suxuantv.cookie.SPCookieStore
import com.suxuantech.erpsys.CRM
import com.suxuantech.erpsys.MC
import com.suxuantech.erpsys.OA
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit


/**
 * A login screen that offers login via email/password.
 */
class LoginActivity : BaseActivity() {
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private var mAuthTask: UserLoginTask? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        email.requestFocus()
        val id = SPUtils.getInstance().getString(COMPANY_ID)
        if (!id.isNullOrEmpty()) {
            company_id.setText(id)
            email.requestFocus()
            getCompanyDomainById(id, true)
        }

        password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
            if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                attemptLogin()
                return@OnEditorActionListener true
            }
            false
        })

        email_sign_in_button.setOnClickListener { attemptLogin() }
        company_id.setOnFocusChangeListener({ v, hasFocus ->
            if (hasFocus) {
                //  Contact.reSetCompanyDomain()
                company_id.setText("")
                company_id.setFilters(arrayOf<InputFilter>(InputFilter.LengthFilter(10)))
                company_id.addTextChangedListener(textWatcher)
            }
        })
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private fun attemptLogin() {
        if (mAuthTask != null) {
            return
        }
        // Reset errors.
        email.error = null
        password.error = null
        company_id.error = null
        // Store values at the time of the login attempt.
        val emailStr = email.text.toString()
        val idStr = company_id.text.toString()
        val passwordStr = password.text.toString()
        var cancel = false
        var focusView: View? = null
        // Check for a valid id, if the user entered one.
        if (TextUtils.isEmpty(idStr)) {
            company_id.error = getString(R.string.error_incorrect_id)
            focusView = company_id
            cancel = true
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(emailStr)) {
            email.error = getString(R.string.error_field_required)
            focusView = email
            cancel = true
        }
        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(passwordStr)) {
            password.error = getString(R.string.error_field_required)
            focusView = password
            cancel = true
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView?.requestFocus()
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true)
            //   mAuthTask = UserLoginTask(emailStr, passwordStr)
            loginH5(emailStr, passwordStr)
            //mAuthTask!!.execute(null as Void?)
        }
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private fun showProgress(show: Boolean) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
            login_form.visibility = if (show) View.GONE else View.VISIBLE
            login_form.animate()
                    .setDuration(shortAnimTime)
                    .alpha((if (show) 0 else 1).toFloat())
                    .setListener(object : AnimatorListenerAdapter() {
                        override fun onAnimationEnd(animation: Animator) {
                            login_form.visibility = if (show) View.GONE else View.VISIBLE
                        }
                    })

            login_progress.visibility = if (show) View.VISIBLE else View.GONE
            login_progress.animate()
                    .setDuration(shortAnimTime)
                    .alpha((if (show) 1 else 0).toFloat())
                    .setListener(object : AnimatorListenerAdapter() {
                        override fun onAnimationEnd(animation: Animator) {
                            login_progress.visibility = if (show) View.VISIBLE else View.GONE
                        }
                    })
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            login_progress.visibility = if (show) View.VISIBLE else View.GONE
            login_form.visibility = if (show) View.GONE else View.VISIBLE
        }
    }


    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    inner class UserLoginTask internal constructor(private val mEmail: String, private val mPassword: String) : AsyncTask<Void, Void, Boolean>() {

        override fun doInBackground(vararg params: Void): Boolean? {
            // TODO: attempt authentication against a network service.

            try {
                // Simulate network access.
                Thread.sleep(2000)
            } catch (e: InterruptedException) {
                return false
            }

            return DUMMY_CREDENTIALS
                    .map { it.split(":") }
                    .firstOrNull { it[0] == mEmail }
                    ?.let {
                        // Account exists, return true if the password matches.
                        it[1] == mPassword
                    }
                    ?: true
        }

        override fun onPostExecute(success: Boolean?) {
            mAuthTask = null
            showProgress(false)

            if (success!!) {
                finish()
            } else {
                password.error = getString(R.string.error_incorrect_password)
                password.requestFocus()
            }
        }

        override fun onCancelled() {
            mAuthTask = null
            showProgress(false)
        }
    }


    companion object {
        /**
         * A dummy authentication store containing known user names and passwords.
         * TODO: remove after connecting to a real authentication system.
         */
        private val DUMMY_CREDENTIALS = arrayOf("foo@example.com:hello", "bar@example.com:world")
    }


    /**
     *根据id获取公司域名
     */
    fun getCompanyDomainById(companyID: String, b: Boolean = false) {
        Contact.MC=""
        Contact.OA=""
        if (companyID.isEmpty()) {
            company_id.addTextChangedListener(textWatcher);
            company_id.requestFocus();
            return
        }
        showProgress(true)
        val url = Contact.COMPANY_DOMAIN
        val body = FormBody.Builder()
        body.add("app_code", companyID)
        var key = "app_code=" + companyID + Contact.CONTACT_KEY
        key = EncryptUtils.encryptMD5ToString(key).toUpperCase()
        val request = Request.Builder()
        request.url(url)
        request.addHeader("ACCESS-TOKEN", key)
        request.post(body.build())
        //强制網絡获取
        val build = CacheControl.Builder().noCache().build();
        request.cacheControl(build)
        val cache = Cache(cacheDir, 1024 * 1024 * 10)
        val client = OkHttpClient.Builder().cache(cache).build()
        val call = client.newCall(request.build())
        call.enqueue(object : Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                Log.d("失败",e?.message)
                runOnUiThread {
                    showProgress(false)
                }
            }
            override fun onResponse(call: Call, response: Response) {
                runOnUiThread {
                    showProgress(false)
                }
                val toString = response.body()?.string()
                LogUtils.d("数据：$toString")
                val parse = JSON.parseObject(toString)
                val msg = parse.getString("msg")
                val code = parse.getString("code")
                if (code.equals("200")) {
                    setCompanyName(msg)
                    val data = parse.getJSONArray("data")
                    for (i in data.indices) {
                        val item = data.getJSONObject(i)
                        var domain = item.getString("api_url")
                        val suxuanProdcutId = item.getString("configuration_id")
                        //为空不执行，直接下一个
                        if (domain.isNullOrEmpty()) {
                            continue
                        }
                        // 规范化
                        if (domain.endsWith("/")) {
                            domain = domain.substring(0, domain.length - 1);
                        }

                        if (!domain.startsWith("http://")) {
                            domain = "http://" + domain;
                        }

                        when (suxuanProdcutId) {
                            MC -> {
                                Contact.MC = domain
                                LogUtils.d("数据MC$domain")
                            }
                            CRM -> {
                                Contact.CRM = domain
                                runOnUiThread {
                                    email.requestFocus()
                                }
                            }
                        }

                    }
                    SPUtils.getInstance().put(COMPANY_ID, companyID);
                    LogUtils.d("数据data$data")
                    runOnUiThread {
                        val name = SPUtils.getInstance().getString(NAME)
                        val pwd = SPUtils.getInstance().getString(PWD)
                        if (!name.isNullOrEmpty()) {
                            password.setText(pwd)
                            email.setText(name)
                            email_sign_in_button.requestFocus()
                            if(b){
                                loginH5(name,pwd)
                            }
                        }
                    }

                }else{
                    ToastUtils.showShort(msg)
                }
            }
        })
    }


    fun setCompanyName(str: String) {
        runOnUiThread {
            company_id.setFilters(arrayOf(InputFilter.LengthFilter(Int.MAX_VALUE)))
            company_id.setText(str)
        }
    }

    var textWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
        override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {


        }

        override fun afterTextChanged(editable: Editable) {
            if (editable.length == 10) {
                getCompanyDomainById(editable.toString())
            }
        }
    }

    /**
     * 登录
     * 妈的这里应该是另一个h5的登录，不是客户端的
     */
    fun loginH5(name: String, pwd: String) {
        showProgress(true)
        val fullUrl = Contact.getFullUrl(Contact.crm_login)
        //保存的body
        val body = FormBody.Builder()
        body.add("staffname", name);
        body.add("password", pwd);
        body.add("five", 0.toString());
        //head 与body添加
        val request = Request.Builder()
        LogUtils.d("数据：$fullUrl")
        if (!fullUrl.startsWith("http://") && !fullUrl.startsWith("https://")) {
            ToastUtils.showShort("域名错误")
            showProgress(false)
            return
        }
        request.url(fullUrl)
        request.addHeader("X-Requested-With", "XMLHttpRequest")
        request.addHeader("Content-Type", "application/x-www-form-urlencoded")
        request.post(body.build())
        //强制网络获取
        val build = CacheControl.Builder().noCache().build();
        request.cacheControl(build)
        val cache = Cache(cacheDir, 1024 * 1024 * 10)
        //客户端
        val c = CookieJarImpl(SPCookieStore(this))
        val client = OkHttpClient.Builder().cache(cache)
                .connectTimeout(10, TimeUnit.SECONDS).writeTimeout(15, TimeUnit.SECONDS) //设置超时
                .cookieJar(c).build()
        //客户端发起请求
        val call = client.newCall(request.build())
        call.enqueue(object : Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                runOnUiThread {
                    password.requestFocus()
                    showProgress(false)
                }
            }

            override fun onResponse(call: Call, response: Response) {
                runOnUiThread {
                    password.requestFocus()
                    showProgress(false)
                }
                val list = CookieUtil.cookieList()
                val allCookie = c.cookieStore.allCookie;
                val c = CookieUtil.getCookie()
                val toString = response.body()?.string()
                LogUtils.d("数据：$toString")
                val parse = JSON.parseObject(toString)
                val msg = parse.getString("msg")
                val code = parse.getString("code")
                if (code.equals("200")) {
                    SPUtils.getInstance().put(NAME, name);
                    SPUtils.getInstance().put(PWD, pwd);

                    runOnUiThread {

                        startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                        finish()
                    }

                } else {
                    runOnUiThread {
                        ToastUtils.showShort(msg)
                    }
                }

            }
        })
    }
}
